/**
 * Created with IntelliJ IDEA.
 * User: teddy zhang
 * Date: 2015-06-08
 * Time: 16:24
 */

define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    
    $.widget('rk.workreportStatisticCtrl', {
        //create方法中用来生成html
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            opt.randomkey = Math.random() + '';

            var globalDATA = globalDATA || {};
            globalDATA = {
                'day': {
                    type: 'day',
                    step: 7,
                    defaultDay: moment().day(1).format('YYYY-MM-DD')
                },
                'week': {
                    type: 'month',
                    step: 1,
                    defaultDay: moment().startOf('month').format('YYYY-MM-DD')
                },
                'month': {
                    type: 'year',
                    step: 1,
                    defaultDay: moment().startOf('month').format('YYYY-MM-DD')
                }
            };
            opt.data = globalDATA;
            opt.type = 'day';
            rk.get('/json/oa_workreport/init-report.action', function(data) {
                if (data.status === 0) {
                    data = data.data;
                    me._render();
                    me._bind(data);
                    me._search(1);
                }
            });
            this.button1 = elem.find('.xxx .xx');
        },
        _bind: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            $("#wrStatisticUser").rkUser({
                onSelect: function(userId, userName) {
                    elem.find('.area_select a.search-close').show();
                    me._search(1);
                }
            });

            $("#wrStatisticDepartment").singletreeselector({
                position: {
                    my: 'left top+2'
                },
                width: 180,
                source: '/json/crm_dimension/dim-tree.action?dimType=1&belongId=25',
                onSuccess: function(o) {
                    $("#wrStatisticUser").val('');
                    elem.find('.area_select a.search-close').hide();
                    me._search(1);
                    //elem.find('div.workreport-grid-body').beScroll();
                }
            }).singletreeselector('val', {
                value: data.entity.departId,
                label: data.entity.departName
            });

            elem.find('.area_select a.search-close').on('click', function(event) {
                var _this = this;
                $("#wrStatisticUser").val('');
                elem.find('.area_select a.search-close').hide();
                me._search(1);
            });


            elem.find('.work-report-div ul li').on('click', function(event) {
                var _this = this;
                elem.find('.goal_top_title span.view_name').attr('data-value', $(_this).find('a').attr('data-value')).html($(_this).find('a').text());
                opt.type = $(_this).find('a').attr('data-name');
                elem.find('.workreport-schedule-header  span.date-content').attr('data-value', opt.data[opt.type].defaultDay);
                me._changeHeader(moment(elem.find('.workreport-schedule-header  span.date-content').attr('data-value')));
                me._search(1);
            });

            elem.find('.goal_top_title .view_now').on('click', function(event) {
                $(me).attr("randomkey", opt.randomkey);
                elem.find('.goal_top_title .work-report-div').toggle();
                me._registerToBodyClick();
                return false;
            });

            elem.find('.workreport-schedule-header a.prve').on('click', function(event) {
                me._changeHeader(moment(elem.find('.workreport-schedule-header  span.date-content').attr('data-value')).add(-parseInt(opt.data[opt.type].step), String(opt.data[opt.type].type)));
                me._search(1);
                return false;
            });

            elem.find('.workreport-schedule-header a.next').on('click', function(event) {
                me._changeHeader(moment(elem.find('.workreport-schedule-header  span.date-content').attr('data-value')).add(parseInt(opt.data[opt.type].step), String(opt.data[opt.type].type)));
                me._search(1);
                return false;
            });
        },

        _generateHeader: function(baseDate) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var param = {
                date_range_text: ''
            };
            var newDate = moment(baseDate);
            switch (opt.type) {
                case 'day':
                    param = {
                        statistic_day_range: moment(baseDate).day(1).format(rk.i18n('WORKREPORT_4')) + " - " + moment(baseDate).day(7).format(rk.i18n('WORKREPORT_4')),
                        data_startTime: moment(baseDate).day(1).format('YYYY-MM-DD'),
                        data_endTime: moment(baseDate).day(7).format('YYYY-MM-DD'),
                        data_value: moment(baseDate).day(1).format('YYYY-MM-DD'),
                        date_range_text: $.map(rk.i18n('WORKREPORT_5').split('|'), function(value, index) {
                            var _day = moment(baseDate).day(index + 1);
                            var _day_end = moment(baseDate).day(index + 1).add(1, 'days');
                            return '<th data-name ="' + _day.format('DD') + '" data-startTime="' + _day.format('YYYY-MM-DD') + '" ' + '" data-endTime="' + _day_end.format('YYYY-MM-DD') + '" ' + (_day.format('DD') == moment().format('DD') ? ' class="active">' : '>') + '<span><em>' + _day.format('DD') + '</em>' + value + '</span></th>';
                        }).join(''),
                        dateYear: newDate.year() + rk.i18n('WORKREPORT_6'),
                        dateContent: newDate.format(rk.i18n('WORKREPORT_4')) + " - " + baseDate.add(6, 'days').format(rk.i18n('WORKREPORT_4'))
                    };

                    break;
                case 'week':
                    var first = moment(baseDate).date(1);
                    var last = moment(first).add(1, 'month').date(0);
                    first = first.day() == 0 ? moment(first).day(-6) : moment(first).day('Monday');
                    last = last.day() == 0 ? last : moment(last).day(7);

                    var minDay = false;
                    var maxDay = false;

                    for (var i = first; i.unix() < last.unix(); i.add(7, 'day')) {
                        var _firstDay =i;
                        var _lastDay = moment(i).add(6, 'day');
                        if (!minDay) minDay = moment(_firstDay);
                        maxDay = moment(_lastDay);
                        var _date_range = _firstDay.format(rk.i18n('WORKREPORT_4')) + ' - ' + _lastDay.format(rk.i18n('WORKREPORT_4'));
                        var _today = (_firstDay.unix() <= moment().unix()) && (_lastDay.unix() > moment().unix());
                        param.date_range_text += '<th' + ' data-startTime="' + _firstDay.format('YYYY-MM-DD') + '" ' + '" data-endTime="' + _lastDay.format('YYYY-MM-DD') + '" ' + (_today ? ' class="active">' : '>') + '<span>' + _date_range + '</span></th>';
                    }
                    param.statistic_day_range = moment(baseDate).format(rk.i18n('WORKREPORT_7'));
                    param.statistic_value = moment(baseDate).format('YYYY-MM');
                    param.data_startTime = minDay.format('YYYY-MM-DD');
                    param.data_endTime = maxDay.format('YYYY-MM-DD');
                    param.data_value = moment(baseDate).startOf('month').format('YYYY-MM-DD');
                    param.dateYear = moment(baseDate).year() + rk.i18n('WORKREPORT_6');
                    param.dateContent = moment(baseDate).format(rk.i18n('WORKREPORT_7'));
                    break;
                case 'month':
                    param.statistic_day_range = '';
                    param.data_startTime = moment(baseDate).month(0).date(1).format('YYYY-MM-DD');
                    param.data_endTime = moment(baseDate).month(12).date(0).format('YYYY-MM-DD');
                    param.data_value = moment(baseDate).month(0).date(1).format('YYYY-MM-DD');
                    var day_range_array = [
                        rk.i18n('WORKREPORT_MONTH_1'), 
                        rk.i18n('WORKREPORT_MONTH_2'), 
                        rk.i18n('WORKREPORT_MONTH_3'), 
                        rk.i18n('WORKREPORT_MONTH_4'), 
                        rk.i18n('WORKREPORT_MONTH_5'), 
                        rk.i18n('WORKREPORT_MONTH_6'), 
                        rk.i18n('WORKREPORT_MONTH_7'),
                        rk.i18n('WORKREPORT_MONTH_8'),
                        rk.i18n('WORKREPORT_MONTH_9'),
                        rk.i18n('WORKREPORT_MONTH_10'),
                        rk.i18n('WORKREPORT_MONTH_11'),
                        rk.i18n('WORKREPORT_MONTH_12')];
                    $.each(day_range_array, function(index, value) {
                        var _day = moment(baseDate).month(index).date(1);
                        var _day_end = moment(baseDate).month(index + 1).date(0);
                        var _today = (_day.unix() <= moment().unix()) && (_day_end.unix() > moment().unix());
                        param.date_range_text += '<th style="width: '+6.25+'%" ' + ' data-startTime="' + _day.format('YYYY-MM-DD') + '" ' + '" data-endTime="' + _day_end.format('YYYY-MM-DD') + '" ' + (_today ? ' class="active">' : '>') + '<span>' + value + '</span></th>';
                    });
                    param.dateYear = newDate.year() + rk.i18n('WORKREPORT_6');
                    param.dateContent = '';
                    break;
            }
            param.statistic_year = newDate.format(rk.i18n('WORKREPORT_8'));
            return param;

        },

        _changeHeader: function(baseDate) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var param = me._generateHeader(baseDate);

            elem.find('.workreport-schedule-header  span.date-content').attr({
                'data-startTime': param.data_startTime,
                'data-endTime': param.data_endTime,
                'data-value': param.data_value
            });

            elem.find('.workreport-schedule-header   span.date-year').html(param.dateYear);
            elem.find('.workreport-schedule-header   span.date-month').html(param.dateContent);
            elem.find('.workreport-grid-header').html(rk.templateText(require('oa/tmpl/workreport/statistic/tpl_workreport_statistic_header.tpl'), param));
        },

        _registerToBodyClick: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            $(document.body).on('click.' + opt.randomkey, function(e) {
                var target = $(e.target);
                if ($(target).parents().attr('randomkey') == opt.randomkey || target.attr('randomkey') == opt.randomkey) {
                    return;
                }
                window.setTimeout(function() {
                    $(document.body).off('click.' + opt.randomkey);
                    $(elem).find('.goal_top_title .work-report-div').hide();
                }, 10);
            });
        },

        _render: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var param = me._generateHeader(moment());
            param.statistic_header = rk.templateText(require('oa/tmpl/workreport/statistic/tpl_workreport_statistic_header.tpl'), param);
            elem.html(rk.templateText(require('oa/tmpl/workreport/statistic/tpl_workreport_statistic.tpl'), param));

        },
        _getSearchData: function(pageNo) {
            var me = this;
            var elem = me.element;

            var postDATA = {};
            postDATA.departId = $("#wrStatisticDepartment").singletreeselector('val').value;
            postDATA.userIds = ($.trim($("#wrStatisticUser").val()) !== '') ? $("#wrStatisticUser").rkUser('getUserId') : '';
            postDATA.belongId = elem.find('.goal_top_title span.view_name').attr('data-value');
            postDATA.startTime = moment(elem.find('.workreport-schedule-header  span.date-content').attr('data-startTime')).toDate().getTime();
            postDATA.endTime = moment(elem.find('.workreport-schedule-header  span.date-content').attr('data-endTime')).toDate().getTime();
            postDATA.page = pageNo;
            return postDATA;
        },
        _getDelayTime: function(data, baseDate) {
            var me = this;
            var elem = me.element;

            var belongId = parseFloat(elem.find('.goal_top_title span.view_name').attr('data-value'));
            if(parseInt(data.delayFlg)){
                if(belongId == 25){
                 return   moment(baseDate).add(parseInt((data.delayDay ? data.delayDay : 365) - 1),'days').toDate().getTime() + parseFloat((data.delayTime ? data.delayTime : 0));
                }
                if(belongId == 26){
                  return moment(moment(baseDate).day(parseInt(data.delayDay ? data.delayDay : 365)+4).hour(0).minutes(0).seconds(0).milliseconds(0).toDate().getTime()+ parseFloat(data.delayTime ? data.delayTime : 0));
                }
             }
        },
        _assembleData: function(data) {
            var me = this;
            var elem = me.element;

            var REPORT_STATISTIC_SUM_COMMITTED = 1;
            var REPORT_STATISTIC_SUM_UNCOMMITTED = 2;
            var REPORT_STATISTIC_SUM_DELAYED = 3;
            var REPORT_STATISTIC_EMPTY = 4;

            var userIdTimeMap = data.userIdTimeMap;
            var statisticDATA = [];
            $.each(userIdTimeMap, function(userId, dateTime) {
                var committed_sum = 0;
                var un_committed_sum = 0;
                var delay_sum = 0;
                var rowData = [data.users[userId], 0, 0, 0];
                $.each(elem.find('.workreport-grid-inner .workreport-grid-header thead th:gt(3)'), function(index, th) {
                    var th_createdAt = 0;
                    var th_value = $(th).attr('data-startTime');
                    var th_startTime = moment($(th).attr('data-startTime')).hour(0).minutes(0).seconds(0).toDate().getTime();
                    var th_endTime = moment($(th).attr('data-endTime')).hour(0).minutes(0).seconds(0).toDate().getTime();
                    var status_flag = REPORT_STATISTIC_SUM_UNCOMMITTED;
                    var timeRangeArray = userIdTimeMap[userId] ? userIdTimeMap[userId].split(',') : [];
                    if ((moment(th_value).unix() - moment().unix() > 0) > 0 || (parseInt(data.belongId) == 25 && (moment(th_value).day() == 0 || moment(th_value).day() == 6) )) {
                        status_flag = REPORT_STATISTIC_EMPTY;
                    } else {
                        $.each(timeRangeArray, function(index, reportDateAndCreatedAt) {
                            var _reportDateAndCreatedAtArray = reportDateAndCreatedAt.split('&');
                            var _reportDate = _reportDateAndCreatedAtArray[0];
                            var _createdAt = _reportDateAndCreatedAtArray[1];
                            var _delayTime = me._getDelayTime(data, th_startTime);
                            if (_reportDate >= th_startTime && _reportDate < th_endTime) {
                                status_flag = REPORT_STATISTIC_SUM_COMMITTED;
                                if(parseInt(data.belongId) != 27 ){
                                    if (_createdAt > _delayTime) {
                                        status_flag = REPORT_STATISTIC_SUM_DELAYED;
                                        th_createdAt = _createdAt;
                                    }
                                }

                            }
                        });

                    }
                    if (status_flag == REPORT_STATISTIC_SUM_COMMITTED) {
                        ++committed_sum
                    } else if (status_flag == REPORT_STATISTIC_SUM_UNCOMMITTED) {
                        ++un_committed_sum;
                    } else if (status_flag == REPORT_STATISTIC_SUM_DELAYED) {
                        ++delay_sum;
                    }
                    rowData.push({
                        'flag': status_flag,
                        'delayTime': th_createdAt ? moment(parseFloat(th_createdAt)).format('YYYY-MM-DD HH:mm') : 0
                    });

                });
                rowData[1] = committed_sum + delay_sum;
                rowData[2] = un_committed_sum;
                rowData[3] = delay_sum;
                statisticDATA.push(rowData);
            });
            return me._sort(statisticDATA);
        },

        _sort: function(data) {
            var sortedDATAArray = [];
            $.each(data, function(index, item) {
                if (item[0] && item[0].id == SESSION.user.id) {
                    sortedDATAArray[0] = item;
                    index--;
                } else {
                    sortedDATAArray[index + 1] = item;
                }
            });
            return $.grep(sortedDATAArray, function(item, i) {
                return (item);
            });
        },
        _search: function(pageNo) {
            var me = this;
            var elem = me.element;

            elem.find('.workreport-grid-body').beLoading({
                size: 'large'
            })
            var param = {};
            rk.post("/json/oa_workreport/analyse-day-report.action", me._getSearchData(pageNo), function(json) {
                if (json.status === 0) {
                    var users = json.data.users;
                    var total = json.data.total;
                    var tbody_content = '';
                    tbody_content = $.map(me._assembleData(json.data), function(rowDATA) {
                        if (!rowDATA[0]) return null;
                        return '<tr>' + $.map(rowDATA, function(val, index) {
                            var html;
                            if (index == 0) { //user
                                html = '<a  target="_blank" href="/final/user.action?id=' + val.id + '">' +
                                    '<span class="avatar"><img src="' + (val.icon ? val.icon : rk.DEFAULT_USER_ICON) + '" ucard="uid=' + val.id + '" ' + '></span>' +
                                    '<span class="name">' + val.name + '</span></a>';
                            } else if (index < 4) { //na san ge
                                html = '<span>' + val + '</span>';
                            } else { //ri qi
                                if (val.flag == 1) {
                                    html = '<span class="has-submit"></span>';
                                } else if (val.flag == 2) {
                                    html = '<span class="no-submit"></span>';
                                } else if (val.flag == 4) {
                                    html = '<span></span>';
                                } else {
                                    html = '<span class="forward_submit" title="' + ''+rk.i18n('WORKREPORT_3')+' ' + val.delayTime + '"></span>';
                                }
                            }
                            return '<td>' + html + '</td>';
                        }).join('') + '</tr>';
                    }).join('');
                    if (!tbody_content) {
                        tbody_content = '<div class="default_page"><div class="ico"></div><p>'+rk.i18n('WORKREPORT_2')+'</p></div>';
                    }
                    var pagingdiv = elem.find("div.workreport-grid-footer .rk-paging");
                    pagingdiv.rkPaging({
                        pagenum: pageNo, //（可选）当前页数，默认1
                        pagesize: 20, //（可选）当前每页显示条数，默认20
                        rowscount: total, //所有数据数
                        onChange: function(pagenum) {
                            me._search(pagenum);
                        }
                    });
                } else if (json.status === 300001) {
                    tbody_content = '<div class="default_page"><div class="ico"></div><p>'+rk.i18n('WORKREPORT_1')+'</p></div>';

                } else {
                    rk.noticeError(rk.i18n('ERROR_SYSTEM'));
                }

                param.data_header = elem.find('.workreport-grid-header table thead tr').html();
                param.data_body = tbody_content;
                elem.find('.workreport-grid-body').html(rk.templateText(require('oa/tmpl/workreport/statistic/tpl_workreport_statistic_content.tpl'), param)).beScroll();
                elem.find('.workreport-grid-header table thead th').each(function(i, el) {
                    elem.find('.workreport-grid-body th').eq(i).width($(el).width());
                })

                elem.find('.workreport-grid-body table.workreport-tab').css('visibility', 'visible');
                elem.find('span.forward_submit').beTip({
                    dir: 'top'
                });

            });


        }
    });
    return {
        init: function() {
            var $crmPanel = rk.showPageView('crm-panel');
            var $contentPanel = $crmPanel.find('.container_content');
            $contentPanel.workreportStatisticCtrl();
        }
    }
});
